#
# Peerscape Firefox extension: components/pyPeerscapeManager.py
#
# Copyright 2009 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Ken Rimey <rimey@hiit.fi>
#          Konrad Markus <konrad.markus@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

from __future__ import with_statement

import os
import sys
import socket
import logging
from xpcom import components

if True:
    # The following sets up Python's module search path appropriately,
    # assuming that this file is in the Firefox extension's components
    # directory, while the Peerscape code is in the pylib directory.
    # (Actually, pythonext automatically adds pylib to the search path.)

    LOCATION_OF_CODE = '../pylib'

    def append_to_search_path(dir, base=LOCATION_OF_CODE):
        here = os.path.abspath(os.path.dirname(__file__))
        there = os.path.normpath(os.path.join(here, base, dir))
        if there not in sys.path:
            sys.path.append(there)

    append_to_search_path('.')
    append_to_search_path('extras')

from peerscape import PATH
from peerscape import DB
from peerscape.daemon.daemon import Daemon

class pyPeerscapeManager:
    """
    Interface for controlling Peerscape within Firefox

    This class and the launch() method will need to be exported through IDL.
    """
    _com_interfaces_ = [components.interfaces.pyIPeerscapeManager]
    _reg_clsid_ = "{a18d5918-3f84-42ee-8d41-3514776bf8ef}"
    _reg_contractid_ = "@p2p-fusion.org/pyPeerscapeManager;1"
    _reg_desc_ = "Peerscape control interface"

    def __init__(self):
        self.daemon = None
        self.logfile = None

    def launch(self, withFTP, FTPPort):
        """
        Launch Peerscape.
        """
        if self.daemon is None:
            socket.setdefaulttimeout(300)
            self.daemon = Daemon(PATH, http=True, ftp=withFTP, ftp_port=FTPPort)
            self.daemon.init()
            self.daemon.start()

    def startLogging(self, level=logging.INFO, filename='peerscape.log'):
        """
        Log to the specified file.

        The filename is relative to the directory in which the
        database is stored.
        """
        base = os.path.dirname(PATH)
        self.logfile = os.path.expanduser(os.path.join(base, filename))

        dir = os.path.dirname(self.logfile)
        if dir and not os.path.exists(dir):
            os.makedirs(dir)

        logging.basicConfig(level=level,
                            filename=self.logfile,
                            format='%(asctime)s %(message)s',
                            datefmt='%Y-%m-%d %H:%M:%S')

    def getLog(self, n=10000):
        """
        Return at most n bytes from the end of the log.
        """
        if self.logfile is None:
            return 'LOGGING NOT STARTED'

        n = min(n, os.path.getsize(self.logfile))
        with open(self.logfile) as f:
            f.seek(-n, os.SEEK_END)
            f.readline()
            return f.read()

    def getNumPendingInvitations(self):
        """
        Return the number of pending invitations.
        """
        db = DB(PATH)
        try:
            return len(db.list_pending_invitations())
        finally:
            db.close()
        
